//index.js
//获取应用实例
const app = getApp()
var WxNotificationCenter = require("../../utils/WxNotificationCenter.js");
var that;
var classId;
var url1 = 'skClassApi/selectShopClass';//左边商品分类接口
var url2 = 'skShopApi/getGoodsListByClass';//右边商品接口

var recommendTabUrl = 'commonModuleApi/topFun';//类目分类接口
var recommendGoodsUrl = 'shopApi/shopInfo';//推荐店铺数据接口

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var latitude;
var longitude;
var cityName;
var address;
var tabId;

Page({
  data: {
    imgUrls: [],  //推荐轮播图
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    swiperCurrent: 0,
    scrollTop: 0,
    curIndex: 0,
    address: '',
    foods: {},
    bestSellers: [],
    winWidth: 0,
    winHeight: 0,
    currentTab: 0,
    hidden: false
  },
  
  selectMenu: function (e) {//闪送店左侧切换
    var index = e.currentTarget.dataset.itemIndex;
    classId = e.currentTarget.id;
    //console.log(classId);
    that.rightDataUpdate(classId);
    this.setData({
      curIndex: index
    });
  },

  swiperchange: function (e) {
    //console.log(e)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  toDetailsTap: function (e) {//跳转到详情
    wx.navigateTo({
      url: "/pages/goods-details/goods-details?id=" + e.currentTarget.dataset.id + "&goodssellid=" + e.currentTarget.dataset.goodssellid
    })
  },

  onLoad: function () {
    wx.showLoading();
    that = this;
    qqmapsdk = new QQMapWX({
      key: 'ELKBZ-SJMCO-6S2WC-SGNUN-N3542-Y2F7J'
    });
    // 注册通知
    WxNotificationCenter.addNotification("addressSelectedNotification", that.getAddress, that);
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // 调用接口
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (res) {
            console.log(res)
            // 渲染给页面
            that.setData({
              address: res.result.formatted_addresses.recommend,
              result: res.result.pois,
              city: res.result.address_component.city
            });
            cityName = res.result.address_component.city;
            address = res.result.formatted_addresses.recommend;
            app.getCity = res.result.address_component.city;
            //console.log(res);
            that.topTabRequest();
          },
        });
      }
    }),

      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                // 用户已经同意小程序使用定位，后续调用 wx.getLocation 接口不会弹窗询问
                wx.getLocation,
                  wx.chooseLocation
              }
            })
          }
        }
      });

  },

  //接口调用顶部类目数据
  topTabRequest: function () {
    wx.request({
      url: app.globalData.requestUrl + recommendTabUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {//这里写你要请求的参数
        cityName: cityName,
        address: address,
        userID: '',
        classFlag: '1',
        deviceType: 'C142001',
        signType: 'MD5'
      },
      success: function (res) {
        //将获取到的json数据，
        console.log(res.data);//打印日志
        var list = res.data.data;
        that.setData({
          //设置数据到控件显示出来
          recommendPage: list[0].name,
        });
        for (var i = 0; i < list.length; ++i) {
          if (list[i].type == 1) {//推荐页面类型
            that.recommendShopRequest(list[i].id)
          }
          else if (list[i].type == 4) {
            //  haveShop :true;//显示闪送店名称
            //  name : list[i].name;
            that.setData({
              //设置数据到控件显示出来
              shopPage: list[i].name,
              id: list[i].id,
              hidden:true
            })
          } else {
            //隐藏闪送店
            // shopPage:null
          }
          // if(list[i].type !=4 ){
          //       that.setData({
          //         show:true
          //       })
          // }

        }
        // });
      }
    })
  },

  recommendShopRequest: function (id) {
    //接口调用推荐店铺数据
    wx.request({
      url: app.globalData.requestUrl + recommendGoodsUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {//这里写你要请求的参数
        shopId: id,
        userId: '',
        deviceType: 'C124001',
        signType: 'MD5'
      },
      success: function (res) {
        wx.hideLoading();
        //将获取到的json数据，
       // console.log(res.data);//打印日志
        var goodsList = res.data.data.goodsModel;
        var list = [];
        for (var i = 0; i < goodsList.length; ++i) {
          if (goodsList[i].modelType == 'C201004') {//热卖排行
            list = goodsList[i].goodsList;
            // list.push(goodsList[i].goodsList);
          }
        }
        that.setData({
          //设置数据到控件显示出来
          imgUrls: res.data.data.adList,
          bestSellers: list,
        })
      }
    })
  },

  leftDataUpdate: function () {

    //console.log(tabId),
      //接口调用左边数据
      wx.request({
        url: app.globalData.requestUrl + url1,
        header: {
          'content-type': 'application/json'
        },
        method: 'POST',
        data: {//这里写你要请求的参数
          shopId: tabId,
          userId: '',
          flag: '1',
          deviceType: 'C142001',
          signType: 'MD5'
        },
        success: function (res) {
          //将获取到的json数据，
          console.log(res.data);//打印日志
          var list = res.data.data;
          that.setData({
            goods: list,
          })
          if (list.length > 0) {
            classId = list[0].id
            //console.log(classId);
            that.rightDataUpdate(classId)
          }
        }
      })
  },

  rightDataUpdate: function (classId) {
    //接口调用右边
    wx.request({
      url: app.globalData.requestUrl + url2,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {//这里写你要请求的参数
        shopId: tabId,
        userId: '',
        classId: classId,
        status: 1,
        deviceType: 'C124001',
        sign: '3c007daeb06aaa0263fcffeab59a7c7a',
        signType: 'MD5'
      },
      success: function (res) {
        //将获取到的json数据，
        var data = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        //console.log(data)//打印日志
        that.setData({
          foods: data.data,
        })
      }
    })
  },

  navigateToLocation: function () {
    wx.navigateTo({
      url: '../location-add/location-add'
    });
  },

  getAddress: function (address) {
    that.setData({
      address: address
    });
  },
  //滑动切换tab
  bindChange: function (e) {
    console.log(e)
    var that = this;
    that.setData({ 
     currentTab: e.detail.current 
      });
    
  },

  swichNav: function (e) {
    console.log(e)
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      });
      tabId = e.currentTarget.id;
      //右边tab点击
      that.leftDataUpdate();
    }
  },
  cb: function (res) {
    setSilde.call(self, res.data.data);
  },


  // onReady: function () {
  //   // 页面渲染完成
  // },
  // onShow: function () {
  //   // 页面显示
  // },
  // onHide: function () {
  //   // 页面隐藏
  // },
  // onUnload: function () {
  //   // 页面关闭
  // },



})
